﻿using System;
using System.Reflection;
using System.Configuration;
using IM.Manage.IDAL;
using IM.Manage.Models;

namespace IM.Manage.DALFactory
{
    public sealed class DataAccess<TEntity> where TEntity : BaseModel
    {
        private static readonly string AssemblyPath = ConfigurationManager.AppSettings["DAL"];
        public DataAccess()
        { }

        //不使用缓存
        private static object CreateObjectNoCache(string AssemblyPath, string classNamespace)
        {
            try
            {
                object objType = Assembly.Load(AssemblyPath).CreateInstance(classNamespace);
                return objType;
            }
            catch//(System.Exception ex)
            {
                //string str=ex.Message;// 记录错误日志
                return null;
            }

        }
        //使用缓存
        private static object CreateObject(string AssemblyPath, string classNamespace)
        {
            object objType = DataCache.GetCache(classNamespace);
            if (objType == null)
            {
                try
                {
                    objType = Assembly.Load(AssemblyPath).CreateInstance(classNamespace);
                    DataCache.SetCache(classNamespace, objType);// 写入缓存
                }
                catch//(System.Exception ex)
                {
                    //string str=ex.Message;// 记录错误日志
                }
            }
            return objType;
        }

        /// <summary>
        /// 创建数据层接口。
        /// </summary>
        public static IBaseDAL<TEntity> CreateDAL()
        {
            return CreateDAL(true);
        }
        public static IBaseDAL<TEntity> CreateDAL(bool isBase)
        {
            Type type = typeof(TEntity);
            string ClassNamespace = isBase ? AssemblyPath + ".BaseDAL`1[[" + type.FullName + "," + type.Assembly.FullName + "]]" : AssemblyPath + "." + typeof(TEntity).Name + "DAL";
            object objType = CreateObject(AssemblyPath, ClassNamespace);
            return (IBaseDAL<TEntity>)objType;
        }
    }
}
